package com.epam.dao.h2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.epam.dao.TeacherDao;
import com.epam.database.ConnectionPool;
import com.epam.entity.Teacher;
import com.epam.entity.User;

public class H2TeacherDao extends H2AbstractEntityDao<Teacher> implements TeacherDao <Teacher>{
	private static Logger LOGGER = LoggerFactory.getLogger(H2TeacherDao.class);
	
	private final static String SELECT_BY_USER_ID = "SELECT t.teacher_id, "
			+ "p.person_name, p.person_iin, p.person_address, p.person_phone,"
			+ "p.person_dateofbirth, t.category"
			+ " FROM users as u inner join persons as p on u.user_id = p.person_id"
			+ " inner join teachers as t on p.person_id = t.person_id"
			+ " WHERE u.user_id=?";
	
	

	@Override
	public Teacher selectByUserId(User user) {
		Teacher teacher = null;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			conn = ConnectionPool.getInstance().takeConnection();
			pst = conn.prepareStatement(SELECT_BY_USER_ID);
			pst.setLong(1, user.getId());
			rs = pst.executeQuery();
			if (rs.next()) {
				teacher = new Teacher(rs.getLong("teacher_id"),user.getUserName(),
						user.getPassword(), user.getRole(), rs.getString("person_name"),
						rs.getString("person_iin"), rs.getString("person_address"),
						rs.getString("person_phone"), rs.getDate("person_dateofbirth"),
						rs.getString("category"));
			}
		} catch (Exception e) {
			LOGGER.warn("Failed to create the object");
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pst != null)
					pst.close();
				if (conn != null) {
					
					ConnectionPool.getInstance().returnConnection(conn);
				}
			} catch (SQLException e) {
				LOGGER.error("Error  closing request SelectTeachereByUserId");
			}
		}
		return teacher;
	}
	
}
